﻿package net.wangit.adm.org;

import net.wangit.MapList;
import net.wangit.Row;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.DBFactory;
import net.wangit.support.TreeFactory;
import net.wangit.user.org.Org;
import net.wangit.user.org.OrgFactory;
import net.wangit.util.Checker;
import net.wangit.view.tree.Tree;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class OrgTreeFactory extends TreeFactory {

	private static final Log log = LogFactory
			.getLog(net.wangit.adm.org.OrgTreeFactory.class);
	private static final String ICON = "/domain/adm/u/organization.png";
	private static final String LINK_PREFIX = "/adm/org.roles.do?orgid=";
	private static final String ATTRIBUTE = "oncontextmenu=showMenu()";
	private static final String SQL = "select orgid,parentid,orgname,o from AORG order by o,orgid";

	public OrgTreeFactory() {
	}

	public Tree createTree(String domain) throws Exception {
		DB db = DBFactory.getDB();
		MapList data = db
				.query("select orgid,parentid,orgname,o from AORG order by o,orgid");
		if (Checker.isEmpty(data))
			return null;
		int rootRowIndex = data.findRowIndex("parentid", "");
		if (rootRowIndex < 0)
			rootRowIndex = data.findRowIndex("parentid", null);
		if (rootRowIndex < 0) {
			log.error("could not found the root of role");
			return null;
		} else {
			Tree tree = getTree(data, rootRowIndex);
			return tree;
		}
	}

	private Tree getTree(MapList data, int index) throws Exception {
		Tree tree = new Tree();
		Row row = data.getRow(index);
		String organizationId = row.get("orgid");
		String organizationName = row.get("orgname");
		Org organization = OrgFactory.getOrg(organizationId);
		tree.setId(organizationId);
		setName(tree, organizationId, organizationName,
				organization.getRoles().length, organization.getPrivileges()
						.size());
		tree.setIcon("/domain/adm/u/organization.png");
		setCustomAttribute(tree, organizationId);
		for (int i = 0; i < data.size(); i++) {
			String parent = data.getRow(i).get("parentid");
			if (organizationId.equals(parent))
				tree.add(getTree(data, i));
		}

		return tree;
	}

	protected void setCustomAttribute(Tree tree, String organizationId) {
		tree.setAttribute("oncontextmenu=showMenu()");
		tree.setAction((new StringBuilder("/adm/org.roles.do?orgid=")).append(
				organizationId).toString());
	}

	protected void setName(Tree tree, String orgId, String orgName,
			int roleCount, int privilegeCount) {
		tree.setName((new StringBuilder(String.valueOf(roleCount))).append(" ")
				.append(orgName).append(" (").append(orgId).append(") ")
				.append(privilegeCount).toString());
	}

}
